package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseAuditDto;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.commons.model.dto.CourseDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioConfig;
import com.xuecheng.content.config.MinioProperties;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mappers.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exceptions.BusinessException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Override
    public ResponseResult courseList(PageRequest pageRequest, CourseDto courseDto) {
        Page<CourseBase> pageParam = new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(courseDto.getCourseName())){
            queryWrapper.like(CourseBase::getName,courseDto.getCourseName());
        }
        if (!StringUtils.isEmpty(courseDto.getAuditStatus())){
            queryWrapper.eq(CourseBase::getAuditStatus,courseDto.getAuditStatus());
        }
        if (!StringUtils.isEmpty(courseDto.getTeachmode())) {
            queryWrapper.eq(CourseBase::getTeachmode,courseDto.getTeachmode());
        }
//        queryWrapper.eq(CourseBase::getCompanyId, AuthInfoHolder.getCompanyId());
        IPage<CourseBase> page = this.page(pageParam, queryWrapper);
        return PageResponseResult.okResult(page.getTotal(),page.getRecords());
    }
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;
    @Override
    public ResponseResult upload(String filename, InputStream inputStream) throws Exception {
        String filepath = "/images/"+
                new SimpleDateFormat("yyyy/MM/dd").format(new Date())+ "/" +
                UUID.randomUUID().toString()+filename;
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioProperties.getBucket())
                .contentType("image/jpg")
                .object(filepath)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(args);

        String imageUrl = minioProperties.getDomain() + "/" + minioProperties.getBucket() + "/" + filepath;
        return ResponseResult.okResult(imageUrl);
    }

    @Autowired
    private TeachplanService teachplanService;

    @Transactional(rollbackFor = Exception.class)
    public ResponseResult course(CourseBaseDto courseBaseDto) {
        if (courseBaseDto == null) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        CourseBase courseBase = BeanHelper.copyProperties(courseBaseDto, CourseBase.class);
        courseBase.setStatus(CommonConstants.USING_FLAG);
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        courseBase.setCreateDate(new Date());
        courseBase.setPlanNum(0);
        courseBase.setCompanyId(AuthInfoHolder.getCompanyId());

        boolean save = this.save(courseBase);
        if (!save) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }

        Teachplan teachplan = new Teachplan();
        teachplan.setPname(courseBase.getName());
        teachplan.setParentid(0l);
        teachplan.setGrade(CourseConstants.FIRST_LEVEL);
        teachplan.setCourseId(courseBase.getId());
        teachplan.setStatus(CommonConstants.USING_FLAG);
        teachplan.setCreateDate(new Date());
        teachplanService.save(teachplan);

        Map map = new HashMap();
        map.put("courseBaseId",courseBase.getId());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult updateCourse(CourseBaseDto courseBaseDto) {
        if (courseBaseDto == null) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        CourseBase  newCourseBase = BeanHelper.copyProperties(courseBaseDto, CourseBase.class);
        CourseBase courseBase = this.getById(courseBaseDto.getId());

        String auditStatus = courseBase.getAuditStatus();
        if (!CourseConstants.AUDIT_UNPAST_STATUS .equals(auditStatus) && !CourseConstants.AUDIT_DISPAST_STATUS .equals(auditStatus)){
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }

        boolean update = this.updateById(newCourseBase);
        if (!update) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        Map map = new HashMap();
        map.put("courseBaseId",courseBase.getId());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult commit(Long courseBaseId) {
        CourseBase courseBase = this.getById(courseBaseId);
        if (courseBase == null) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        courseBase.setAuditStatus(CourseConstants.AUDIT_COMMIT_STATUS );
        boolean update = this.updateById(courseBase);
        if (!update) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult approve(CourseAuditDto dto) {
        CourseBase courseBase = this.getById(dto.getCourseBaseId());
        if (courseBase == null) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        courseBase.setAuditStatus(dto.getAuditStatus());
        courseBase.setAuditMind(dto.getAuditMind());
        boolean update = this.updateById(courseBase);
        if (!update) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        return ResponseResult.okResult();
    }
}
